<template>
  <view class="container">
	  <view class="null" v-if="newFans.length<=0">
	  	您目前还没有新增粉丝
	  </view>
    <view v-for="(item, index) in newFans" :key="index" class="fan-item">
      <u-avatar :src="item.avatar" class="avatar" mode="aspectFill" @click="goToPersonalInfomation(item.senderId,item.sender)" />
      <view class="content" @click="goToPersonalInfomation(item.senderId,item.sender)">
        <view class="username">{{ item.sender }}</view>
		<view class="way">通过 {{item.way}}</view>
		<view class="date">在 {{ timeShow(item.time) }} 关注了你</view>
      </view>
      <button :class="['follow-button', !item.isFollowing ? 'following' : 'not-following']" @click="changeFollow(index)">
        {{ !item.isFollowing ? '互相关注' : '已关注' }}
      </button>
    </view>
  </view>
</template>

<script>
import method from '@/utils/methods.js'
	import { mapState } from 'vuex';
export default {
	computed: {
		    ...mapState(['isFansChange']), // 映射 Vuex 状态
		 },
	watch:{
		// isFansChange(newVal, oldVal) {
		// 	this.$store.commit("changeFans",null);
		// }
	},
  data() {
    return {
		uid:null,
		token:null,
      newFans: []
    };
  },
  created() {
  	this.uid=uni.getStorageSync("UID")
  	this.token=uni.getStorageSync("token")
  	this.getFollowers()
  },
  methods:{
	 goToPersonalInfomation(uid,username){
	 	uni.navigateTo({
	 		url:"/pages/personalInformation/personalInformation?uid="+uid+"&username="+username
	 	})
	 },
	 changeFollow(index){
		 if(this.newFans[index].isFollowing==true){
			 //此时要取消关注
			 uni.showModal({
			 	title:"注意",
				content:"确定要取消关注吗？",
				cancelText:"算了",
				confirmText:"我要取关",
				success: (res) => {
					if(res.confirm){
						//向后端发送取消关注请求
						method.cancelFollowUser(this.uid,this.newFans[index].senderId,this.uid,this.token).then((result) => {
							this.newFans[index].isFollowing=false;
							  uni.showToast({
							  	title:result.message,
								icon:"none",
								duration:500
							  })
						})
						.catch((error) => {
							uni.showToast({
								title:error.message,
								icon:"none",
								duration:2000
							})
						});
					}else{
						return;
					}
				}
			 })
		 }else{
			//此时向后发送关注请求
			method.followUser(this.uid,this.newFans[index].senderId,this.uid,this.token,"新增粉丝").then((result) => {
				this.newFans[index].isFollowing=true;
				  uni.showToast({
				  	title:result.message,
					icon:"none",
					duration:500
				  })
			})
			.catch((error) => {
				uni.showToast({
					title:error.message,
					icon:"none",
					duration:2000
				})
			});
		 }
		 
	 },
	 getFollowers(){
		 //不需要请求，而是根据websocket通知消息插入
		uni.request({
			url: this.baseUrl+"/user/getUserFollowers/"+this.uid,
			method:"GET",
			header:{
				token:this.token,
				uid:this.uid
			},
			success: (res) => {
				if(res.data.code=1){
					const fans=uni.getStorageSync('fansList')||[]
					// console.log(fans[0].senderId)
					const users=res.data.data||[];
					// console.log(users[0].uid)
					users.forEach((user)=>{
						const imgBase64 = user.avatar.userAvatar
						const imgExtension = user.avatar.imgType;
						var way;
						var index = fans.findIndex(fan => (fan.senderId) === (user.uid));
						if (index === -1) {
						    console.log("没找到本地记录，设置为默认关注");
						    way = "默认关注"; // 如果没有找到，设置默认值
						} else {
						    way = fans[index].way || "默认关注"; // 如果找到，使用找到的值
						    // console.log(fans[index]);
						}
						// 连接成 Data URL
						const imgType = imgExtension; // 使用后缀名作为 MIME 类型
						const dataUrl = "data:image/" + imgType + ";base64," + imgBase64;
						this.newFans.unshift({
							senderId:user.uid,
							sender:user.username,
							isFollowing:user.isFollow,
							way,
							time:user.time,
							avatar:dataUrl
						})
					})
				}else{
					
				}
			}
		}) 
	 },
	 timeShow(timestamp){
	 		 const now = new Date();
	 		    const messageTime = new Date(timestamp);
	 		    const diffInSeconds = Math.floor((now - messageTime) / 1000);
	 		    
	 		    if (diffInSeconds < 60) {
	 		        return '刚刚';
	 		    } else if (diffInSeconds < 3600) {
	 		        const minutes = Math.floor(diffInSeconds / 60);
	 		        return `${minutes}分钟前`;
	 		    } else if (diffInSeconds < 86400) {
	 		        const hours = Math.floor(diffInSeconds / 3600);
	 		        return `${hours}小时前`;
	 		    } else {
	 		        const year = messageTime.getFullYear();
	 		                const month = String(messageTime.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
	 		                const day = String(messageTime.getDate()).padStart(2, '0');
	 		                const hour = String(messageTime.getHours()).padStart(2, '0');
	 		                const minute = String(messageTime.getMinutes()).padStart(2, '0');
	 		                
	 		                return `${year}-${month}-${day} ${hour}:${minute}`;
	 		    }
		},
  },
};
</script>

<style>
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}
.fan-item {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  padding: 20rpx;
  background-color: #ffffff;
  border-radius: 8rpx;
  margin:0 20rpx 20rpx 20rpx;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}
.content {
  flex: 1;
}
.username {
  font-weight: bold;
  font-size: 40rpx;
}
.way{
	color: #888;
	font-size: 24rpx;
	margin-top: 20rpx;
}
.date {
  color: #888;
  font-size: 24rpx;
  margin-top: 20rpx;
}
.follow-button {
  padding: 10rpx 30rpx;
  border-radius: 5px;
  font-size: 28rpx;
  transition: 0.5s;
}
.following {
  background-color: #4caf50;
  color: #fff;
}
.not-following {
  background-color: #ddd;
  color: #333;
}
.null{
	padding-top:100rpx ;
		color: lightgray;
		font-size: 30rpx;
		text-align: center;
	}
</style>